<template>
    <div>
        <div id="institutionsTree">
            <el-input
                @clear="initActReModel"
                placeholder="输入关键字进行过滤"
                clearable
                v-model="filterText">
            </el-input>
            <el-tree
                class="filter-tree"
                :data="dataInstitutions"
                :props="defaultInstitutionsProps"
                default-expand-all
                :filter-node-method="filterInstitutionsNode"
                ref="tree"
                show-checkbox
                node-key="institutionsId"
                :check-strictly="true"
                @check-change="handleCheckChange"
    	        @node-click="nodeClick">
                <!-- 处理菜单内容过长 -->
                    <span class="custom-tree-node" slot-scope="{ node }">
                        <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start">
                            <span > {{ node.label | ellipsis(8) }} </span>
                        </el-tooltip>
                    </span>
            </el-tree>
        </div>

        <div id="pageList" style="margin-left: 200px;">
            <div class="addActReModel">
              <!-- 筛选条件 -->
                <div style="float: left;display: flex;">
                    <el-input
                            @clear="initActReModel"
                            clearable
                            prefix-icon="el-icon-search"
                            placeholder="请输入模型名称"
                            class="initActReModel"
                            v-model="modelPage.modelName"
                            @keydown.enter.native="initActReModelQuery">
                    </el-input>
                    <el-button style="margin-left: 8px;" icon="el-icon-search" type="info" @click="initActReModelQuery">查询</el-button>
                </div>
                <!-- 右上角区域 -->
                <div style="display: flex;justify-content: flex-end">
                    <el-button
                            type="primary"
                            title="清空查询条件"
                            @click="resetCondition"><i class="el-icon-remove"></i><span>重置</span>
                    </el-button>
                    <el-button
                            type="primary"
                            title="通过流程模型编号部署流程"
                            @click="processDeploy"><i class="el-icon-upload"></i><span>流程部署</span>
                    </el-button>
                    <el-button
                            type="primary"
                            title="通过流程模型编号初始化流程图"
                            @click="processDesign"><i class="el-icon-rank"></i><span>流程设计</span>
                    </el-button>
                    <el-button
                            type="primary"
                            title="新增流程模型与业务表单绑定"
                            @click="insertActReModel"><i class="el-icon-add-location"></i><span>新增模型</span>
                    </el-button>
                </div>
            </div>
            <div>
            <!-- 列表区域 -->
                <el-table
                        :data="ActReModelList"
                        stripe
                        border
                        style="width: 100%"
                        v-loading="loading"
                        element-loading-text="正在加载..."
                        element-loading-spinner="el-icon-loading"
                        element-loading-background="rgba(0, 0, 0, 0.8)"
                        @selection-change="handleSelectionChange">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            label="模型名称"
                            width="200">
                        <template slot-scope="scope">
                        <!-- 卡片展示 -->
                            <el-popover trigger="hover" placement="top">
                                <p>模型编号: {{ scope.row.modelId }}</p>
                                <p>修订版本: V{{ scope.row.revision }}</p>
                                <p>模型名称: {{ scope.row.modelName }}</p>
                                <p>模型KEY: {{ scope.row.modelKey }}</p>
                                <p>模型类别: {{ scope.row.categoryName }}</p>
                                <p>创建时间: {{ scope.row.createTime | dateFormat('YYYY-MM-DD HH:mm:ss')}}</p>
                                <p>更新时间: {{ scope.row.lastUpdateTime | dateFormat('YYYY-MM-DD HH:mm:ss')}}</p>
                                <p>模型版本: V{{ scope.row.version }}</p>
                                <p>部署编号: {{ scope.row.deploymentId }}</p>
                                <p>bpmn资源编号: {{ scope.row.editorSourceValueId }}</p>
                                <p>png资源编号: {{ scope.row.editorSourceExtraValueId }}</p>
                                <p>机构名称: {{ scope.row.tenantName }}</p>
                                <p>表单编号: {{ scope.row.generatorId }}</p>
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">{{ scope.row.modelName }}</el-tag>
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="模型类别"
                            width="200">
                        <template slot-scope="scope">
                            <span>{{ scope.row.categoryName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="所属部门"
                            width="150">
                        <template slot-scope="scope">
                            <span>{{ scope.row.tenantName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="模型版本"
                            width="100">
                        <template slot-scope="scope">
                            <span>V{{ scope.row.version }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="修订版本"
                            width="100">
                        <template slot-scope="scope">
                            <span>V{{ scope.row.revision }}</span>
                        </template>
                    </el-table-column>
                <el-table-column
                        label="创建时间" width="200">
                    <template slot-scope="scope">
                        <span>{{scope.row.createTime| dateFormat('YYYY-MM-DD HH:mm:ss')}}</span>
                    </template>
                </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button
                                    title="流程模型编辑"
                                    @click="updateActReModel(scope.row)"><i class="el-icon-edit"></i>编辑</el-button>
                            <el-button
                                    type="danger"
                                    title="级联删除bpmn|png文件和部署所有相关数据(最近一次部署)、普通表单关系"
                                    @click="deleteActReModel(scope.row)"><i class="el-icon-delete"></i>删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="display: flex;justify-content: flex-end;margin-top: 8px;">
                    <el-pagination
                            background
                            @current-change="currentChange"
                            @size-change="sizeChange"
                            layout="sizes, prev, pager, next, jumper, ->, total, slot"
                            :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
        <!-- 新增模型|编辑模型弹框 -->
        <div>
            <el-dialog
                    :title="title"
                    :visible.sync="dialogVisible"
                    width="60%">
                <div>
                    <el-form :model="ActReModel" :rules="rules" ref="ActReModelForm">
                        <el-row>
                            <el-col>
                                <el-form-item label="模型名称:" prop="actReModelName">
                                    <el-input style="margin-left: -163px;width: 850px;" prefix-icon="el-icon-edit" v-model="ActReModel.actReModelName"
                                              placeholder="请输入模型名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="模型编码:" prop="processKey">
                                    <el-input style="margin-left: -163px;width: 850px;" prefix-icon="el-icon-edit" v-model="ActReModel.processKey"
                                              placeholder="请输入模型key前缀"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item label="模型类别:" prop="categoryName">
                                        <!-- 树形选择框 -->
                                        <tree-select style="margin-left: 90px;width: 850px;"
                                        :options="categoryTreeList"
                                        placeholder="请选择所属类别"
                                        v-model="ActReModel.categoryName"
                                        />
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="使用表单:" prop="generatorId">
                                   <el-select clearable style="margin-left: -163px;width: 850px;" v-model="ActReModel.generatorId" placeholder="请选择">
                                    <el-option
                                    v-for="item in generatorTreeList"
                                    :key="item.generatorId"
                                    :label="item.formDescription"
                                    :value="item.generatorId"/>
                                </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                          <el-col>
                                <el-form-item label="所属部门:" prop="tenantId" >
                                <!-- 树形选择框 -->
                                    <tree-select style="margin-left: 90px;width: 850px;"
                                      :options="BtAccountInstitutionsInfoTreeList"
                                      placeholder="请选择所属机构"
                                      v-model="ActReModel.tenantId"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col >
                                <el-form-item label="描述信息:" prop="metaInfo" >
                                    <el-input style="margin-left: -163px;width: 850px;" type="textarea" rows="4" prefix-icon="el-icon-edit" v-model="ActReModel.metaInfo"
                                              placeholder="请输入模型描述信息"></el-input>
                                </el-form-item>
                            </el-col>
                          </el-row>
                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="insertActReModelRequest">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>

import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
    name:"workflowActReModel",
    components: { TreeSelect },
    data(){
        return{
            flag: false,
            loading: false,
            filterText: '',
            // 查询目录属性设置
            defaultInstitutionsProps:{
                children: 'children',
                label: 'institutionsName'
            },
            // 初始化机构目录
            dataInstitutions:[],
            // 封装查询条件
            modelPage:{
                modelName:'',
                tenantId:'',
                pageNum: 1,
                pageSize: 10
            },
            // 初始化列表
            ActReModelList:[],
            total: 0,
            // 编辑框数据传输
            ActReModel:{
                categoryName:'',
                actReModelName:'',
                actReModelId:'',
                tenantId:'',
                generatorId:'',
                processKey:'',
                metaInfo:''
            },
            // 弹框初始化设置
            title: '',
            dialogVisible: false,
            // 校验规则
            rules: {
                actReModelName:[{required:true,message:'请输入模型名称',trigger:'blur'}],
                categoryName:[{required: true, message: '请选择模型类别', trigger: 'blur'}],
                tenantId:[{required:true,message:'请选择所属部门',trigger:'blur'}],
                processKey:[{required: true, message: '请输入模型KEY前缀', trigger: 'blur'}],
                generatorId:[{required:true,message:'请选择使用表单',trigger:'blur'}],
                metaInfo:[{required: true, message: '请输入模型描述', trigger: 'blur'}]
            },
            // 所属机构
            BtAccountInstitutionsInfoTreeList:[],
            // 所属类别
            categoryTreeList:[],
            // 关联表单
            generatorTreeList:[],
            // 政治面貌
            politicalLandscapesSelect:[],
            // 模型详情
            ActReModelInfo:{},
            ActReModelInfoFlag: false,
            // 初始化多选复选框(实际判断只允许单选)
            multipleSelection:[]
        }
    },
    mounted(){
        // 初始化模型列表
        this.initActReModelQuery();
        // 初始化机构目录
        this.selectBtAccountInstitutionsInfoTreeList();
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      // 监听模型类别编号
      'ActReModel.categoryName': 'queryGeneratorInit'
    },
    methods:{
        handleSelectionChange(val){
            this.multipleSelection = val;
        },
        // 流程设计》》》跳转到流程绘制页面
        processDesign(){
            if (this.multipleSelection.length==1) {
                let modelId = '';
                this.multipleSelection.forEach(item=>{
                    modelId = item.modelId;
                })
                this.$router.push({
                    path: '/drowProccessImageInner',
                    // 参数传递
                    query: {
                        modelId:modelId
                    }
                })
            }else{
                 this.$message({
                        type: 'warning',
                        message: '请选择一条操作记录！'
                });
            }
        },
        // 流程部署
        processDeploy(){
            if (this.multipleSelection.length==1) {
                let modelId = '';
                this.multipleSelection.forEach(item=>{
                    modelId = item.modelId;
                })
                this.putRequest("/activity/ActReModel/deploy/ProcessModelXMLInformationByModelId/"+modelId).then(resp => {
                    if (resp) {
                        console.log("部署成功>>>"+resp.data);
                        this.initActReModelQuery();
                    }
                })
            }else{
                 this.$message({
                        type: 'warning',
                        message: '请选择一条操作记录！'
                });
            }
        },
        // 编辑|新增请求
        insertActReModelRequest(){
            if (this.ActReModel.actReModelId) {
                    this.$refs['ActReModelForm'].validate(valid => {
                        if (valid) {
                            this.putRequest("/activity/ActReModel/update/ProcessModel", this.ActReModel).then(resp => {
                                if (resp) {
                                    this.initActReModelPut();
                                    this.initActReModelQuery();
                                    this.dialogVisible = false;
                                }
                            })
                        }
                    });
            } else {
                this.$refs['ActReModelForm'].validate(valid => {
                    if (valid) {
                        this.postRequest("/activity/ActReModel/insert/ProcessModel", this.ActReModel).then(resp => {
                            if (resp) {
                                this.initActReModelPut();
                                // 初始化列表
                                this.initActReModelQuery();
                                this.dialogVisible = false;
                            }
                        })
                    }
                });
            }
        },
        // 新增模型
        insertActReModel(){
            this.title = "新增模型";
            this.dialogVisible = true;
            this.initActReModelPut();
            this.queryBtAccountInstitutionsInfoTreeList();
            this.queryCategoryTreeList();
            this.queryGeneratorTreeList();
        },
        // 编辑模型
        updateActReModel(data){
            this.title = "编辑模型";
            this.dialogVisible = true;
            this.ActReModel.categoryName = data.category;
            this.ActReModel.actReModelName = data.modelName;
            this.ActReModel.actReModelId = data.modelId;
            this.ActReModel.tenantId = data.tenantId;
            this.ActReModel.generatorId = data.generatorId;
            this.ActReModel.processKey = data.modelKey;
            let modelDescriptio = JSON.parse(data.metaInfo);
            this.ActReModel.metaInfo = modelDescriptio.modelDescriptio;
            this.queryBtAccountInstitutionsInfoTreeList();
            this.queryCategoryTreeList();
            this.queryGeneratorTreeList();
        },
        // 初始化弹框信息
        initActReModelPut(){
            this.ActReModel.categoryName = 'init_level';
            this.ActReModel.actReModelName = '';
            this.ActReModel.actReModelId = '';
            this.ActReModel.tenantId = 'init_level';
            this.ActReModel.generatorId = '';
            this.ActReModel.processKey = '';
            this.ActReModel.metaInfo = '';
        },
        // 刷新查询
        queryGeneratorInit(val){
            console.log('queryGeneratorInit',val);
            if (val) {
                this.queryGeneratorTreeList();
            }
        },
        // 按普通表单类别分组查询已经部署的普通表单
        queryGeneratorTreeList(){
            this.getRequest("/activity/GeneratorForm/query/BusinessTableDeployedByCategoryId?categoryId="+this.ActReModel.categoryName).then(resp => {
                if (resp) {
                    this.generatorTreeList = resp.data;
                }
            });
        },
        // 获取流程模型类别层级Tree|获取启用的流程模型类别
        queryCategoryTreeList(){
            this.getRequest("/activity/ActBtCategory/query/ProcessModelCategoryTree").then(resp => {
                if (resp) {
                    let result = [];
                    let data = resp.data;
                    const children = this.getTreeCategory(data);
                    let obj = {}
                    obj.label = '所属类别'
                    obj.id = 'init_level'
                    obj.children = children
                    result.push(obj)
                    this.categoryTreeList = result;
                }
            });
        },
        // 构建树形数据结构
        getTreeCategory (tree) {
            let arr = [];
            if (tree) {
            tree.forEach(item => {
                let obj = {};
                obj.label = item.categoryName;
                obj.id = item.categoryId;
                if(item.children&&item.children.length!==0) {
                   obj.children = this.getTreeCategory(item.children);
                }
                arr.push(obj);
            });
        }
            return arr;
        },
        selectHigh(){
          if(this.flag){
            this.flag = false;
          }else{
            this.selectBtModelLandscapeList();
            this.flag = true;
          }
        },
        // 重置查询条件
        resetCondition(){
            this.$refs.tree.setCheckedNodes([]);
            this.filterText = '';
            this.modelPage.modelName = '';
            this.modelPage.tenantId = '';
            this.initActReModelQuery();
        },
        // 清空查询条件
        initActReModel(){
            this.resetCondition();
        },
        // 机构目录选择
        handleCheckChange(data, checked, node){
            if(checked == true){
                this.filterText = data.institutionsName;
                this.modelPage.tenantId = data.institutionsId;
                this.$refs.tree.setCheckedNodes([data]);
            }
        },
        nodeClick(data,checked,node){
            this.filterText = data.institutionsName;
            this.modelPage.tenantId = data.institutionsId;
            this.$refs.tree.setCheckedNodes([data]);
        },
        // 机构目录节点过滤
        filterInstitutionsNode(value,dataInstitutions){
            if (!value) return true;
            return dataInstitutions.institutionsName.indexOf(value) !== -1;
        },
        // 获取机构目录
        selectBtAccountInstitutionsInfoTreeList(){
            this.getRequest("/account/BtSysInstitutions/select/BtSysInstitutionsTree").then(resp => {
                if (resp) {
                    this.dataInstitutions = resp.data;
                }
            });
        },
        // 初始化模型列表
        initActReModelQuery(){
            this.loading = true;
            this.postRequest("/activity/ActReModel/query/ProcessModelPageList",this.modelPage).then(resp => {
                this.loading = false;
                if (resp) {
                    this.ActReModelList = resp.data.list;
                    this.total = resp.data.total;
                }
            });
        },
        // 获取机构目录
        queryBtAccountInstitutionsInfoTreeList(){
            this.getRequest("/account/BtSysInstitutions/select/BtSysInstitutionsTree").then(resp => {
                if (resp) {
                    let result = [];
                    let data = resp.data;
                    const children = this.getTree(data);
                    let obj = {}
                    obj.label = '所属机构'
                    obj.id = 'init_level'
                    obj.children = children
                    result.push(obj)
                    this.BtAccountInstitutionsInfoTreeList = result;
                }
            });
        },
        // 构建树形数据结构
        getTree (tree) {
            let arr = [];
            if (tree) {
            tree.forEach(item => {
                let obj = {};
                obj.label = item.institutionsName;
                obj.id = item.institutionsId;
                if(item.children&&item.children.length!==0) {
                   obj.children = this.getTree(item.children);
                }
                arr.push(obj);
            });
        }
            return arr;
        },
        // 删除流程模型信息
        deleteActReModel(data){
            this.$confirm('此操作将永久删除【'+data.modelName+'】, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteRequest('/activity/ActReModel/delete/ProcessModel/'+data.modelId).then(resp=>{
                        if (resp){
                            this.initActReModelQuery();
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                });
            });
        },
        // 分页
        sizeChange(currentSize) {
            this.modelPage.pageSize = currentSize;
            this.initActReModelQuery();
        },
        currentChange(currentPage) {
            this.modelPage.pageNum = currentPage;
            this.initActReModelQuery();
        }
    }
}
</script>

<style>
    .addActReModel{
        margin-bottom: 10px;
    }
    #institutionsTree{
        position:absolute;
        width: 180px;
        border: 1px solid #E7E7E7;
        height: 830px;
    }
    .filter-tree{
        overflow: auto;
        flex: 1;
        width: 170px;
        height: 750px;
        margin:  10px;
    }

    #institutionsTree #pageList{
        position:relative;
    }

</style>
